<template>
  <el-dialog
    title="导出Excel"
    :model-value="modelValue"
    @close="onClosed"
    width="30%"
  >
    <el-input v-model="excelName" placeholder="请输入文件名"></el-input>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClosed">关闭</el-button>
        <el-button type="primary" @click="onConfirm" :loading="loading"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue'
import { userManageList } from '@/api/user'
import { USER_RELATIONS } from './Export2ExcelConstants'
const excelName = ref('员工列表')
const loading = ref(false)
defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

const emits = defineEmits(['update:modelValue'])

// 关闭
const onClosed = () => emits('update:modelValue', false)
const onConfirm = async () => {
  loading.value = true
  const { list } = await userManageList()

  // 导入工具包
  const excel = await import('@/utils/Export2Excel.utils.js')
  // 格式化数据
  const data = formatJson(USER_RELATIONS, list)
  excel.export_json_to_excel({
    // excel 表头
    header: Object.keys(USER_RELATIONS),
    // excel 数据
    data,
    // 文件名称
    filename: excelName.value
  })
  loading.value = false
  onClosed()
}

// 当我们使用export_json_to_excel 的时候，我们传递的data数据，它必须是一个二维数组
const formatJson = (headers, rows) => {
  return rows.map((item) => {
    return Object.keys(headers).map((key) => {
      if (headers[key] === 'role') {
        const roles = item[headers[key]]
        return JSON.stringify(roles.map((role) => role.title))
      }
      return item[headers[key]]
    })
  })
}
</script>

<style scoped></style>
